'''
Created on Apr 6, 2012

@author: daoxuandung
'''
import json
from base import BaseHandler
from webapp2_extras import auth
from web import urls
from web import util
from web import base
from google.appengine.ext import ndb
from app.query import post_async
from entity.entity import Event
from entity.entity import Post
import logging

class EventHandler(BaseHandler):
    """
    Show all details belong to an event
    """
    @base.user_data_print
    @ndb.synctasklet
    def get(self):
        template = util.jinja_environment().get_template('event-page.html')
        template_values = {}
        
        # Get event id
        event_id = self.request.params.get('id')
        if event_id:
            event = Event.get_by_id(int(event_id))
            if event:
                template_values = util.ndb_to_dict(event)
                # Query post list
                post_list = yield post_async.get_by_event(event.key)
                post_list = util.ndb_to_list(post_list)
                
                # Add post list to template_values
                template_values["postList"] = json.dumps(post_list)
                
                # Parse location list 
                location_list = util.ndb_keys_to_dict_list(event.locations)
                template_values["locationList"] = json.dumps(location_list)
                template_values["titleList"] = json.dumps(event.locations_titles)
                
                # Parse ticket list 
                ticket_list = util.ndb_keys_to_dict_list(event.tickets)
                template_values["ticketList"] = json.dumps(ticket_list)
                
        else:
            if (auth.get_auth().get_user_by_session() != None):
                template_values["organizer"] = util.get_current_user_name()  
                
        # Add extra user information if available
        template_values = util.add_user_data(self,template_values)
        self.response.out.write(template.render(template_values))
            

app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()